"""
API序列化器
"""
from rest_framework import serializers
from apps.data_source.models import StockBasic, StockDaily, FinancialIndicator


class StockBasicSerializer(serializers.ModelSerializer):
    """股票基本信息序列化器"""
    
    class Meta:
        model = StockBasic
        fields = ['ts_code', 'symbol', 'name', 'area', 'industry', 'market', 'list_date', 'is_hs']


class StockDailySerializer(serializers.ModelSerializer):
    """股票日线数据序列化器"""
    stock_name = serializers.CharField(source='stock.name', read_only=True)
    
    class Meta:
        model = StockDaily
        fields = [
            'id', 'stock', 'stock_name', 'trade_date', 'open', 'high', 
            'low', 'close', 'pre_close', 'change', 'pct_chg', 'vol', 'amount'
        ]
        read_only_fields = fields


class FinancialIndicatorSerializer(serializers.ModelSerializer):
    """财务指标序列化器"""
    stock_name = serializers.CharField(source='stock.name', read_only=True)
    
    class Meta:
        model = FinancialIndicator
        fields = [
            'id', 'stock', 'stock_name', 'end_date', 'eps', 'dt_eps', 
            'total_revenue_ps', 'revenue_ps', 'bps', 'roe', 
            'profit_to_gr', 'op_to_gr', 'debt_to_assets'
        ]
        read_only_fields = fields


class StockDetailSerializer(serializers.ModelSerializer):
    """股票详情序列化器，包含最近日线数据"""
    latest_daily = serializers.SerializerMethodField()
    
    class Meta:
        model = StockBasic
        fields = [
            'ts_code', 'symbol', 'name', 'area', 'industry', 
            'market', 'list_date', 'is_hs', 'latest_daily'
        ]
    
    def get_latest_daily(self, obj):
        """获取最新一条日线数据"""
        try:
            latest = obj.daily_data.order_by('-trade_date').first()
            if latest:
                return {
                    'trade_date': latest.trade_date,
                    'open': latest.open,
                    'high': latest.high,
                    'low': latest.low,
                    'close': latest.close,
                    'change': latest.change,
                    'pct_chg': latest.pct_chg,
                    'vol': latest.vol,
                    'amount': latest.amount,
                }
        except Exception:
            pass
        return None
